<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.json',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="数据库操作 创建数据库  1use study  如果你想查看所有数据库，可以使用 show dbs 命令：刚创建的数据库并不在数据库的列表中， 要显示它，我们需要向 数据库插入一些数据。  查看当前在哪个数据库  12&amp;gt; dbstudy">
<meta name="keywords" content="sql,mongodb">
<meta property="og:type" content="article">
<meta property="og:title" content="mongodb操作教程">
<meta property="og:url" content="https://unix2dos.github.io/p/d34774ef.html">
<meta property="og:site_name" content="Levon&#39;s Blog">
<meta property="og:description" content="数据库操作 创建数据库  1use study  如果你想查看所有数据库，可以使用 show dbs 命令：刚创建的数据库并不在数据库的列表中， 要显示它，我们需要向 数据库插入一些数据。  查看当前在哪个数据库  12&amp;gt; dbstudy">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-09-27T15:36:51.132Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="mongodb操作教程">
<meta name="twitter:description" content="数据库操作 创建数据库  1use study  如果你想查看所有数据库，可以使用 show dbs 命令：刚创建的数据库并不在数据库的列表中， 要显示它，我们需要向 数据库插入一些数据。  查看当前在哪个数据库  12&amp;gt; dbstudy">
  <link rel="canonical" href="https://unix2dos.github.io/p/d34774ef">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>mongodb操作教程 | Levon's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Levon's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">微信:  L6241425</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>时光</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://unix2dos.github.io/p/d34774ef.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Levon">
      <meta itemprop="description" content="Never Give Up">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Levon's Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">mongodb操作教程

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2017-02-13 17:54:46" itemprop="dateCreated datePublished" datetime="2017-02-13T17:54:46+08:00">2017-02-13</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-09-27 23:36:51" itemprop="dateModified" datetime="2019-09-27T23:36:51+08:00">2019-09-27</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/1-编程语言/" itemprop="url" rel="index"><span itemprop="name">1-编程语言</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/1-编程语言/sql/" itemprop="url" rel="index"><span itemprop="name">sql</span></a></span>

                
                
              
            </span>
          

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
        
      
      <span class="post-meta-item-text">Disqus：</span>
    
    <a title="disqus" href="/p/d34774ef.html#comments" itemprop="discussionUrl"><span class="post-comments-count disqus-comment-count" data-disqus-identifier="p/d34774ef.html" itemprop="commentCount"></span></a>
  </span>
  
  
          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              
                <span class="post-meta-item-text">本文字数：</span>
              
              <span>13k</span>
            </span>
          
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              
              <span>12 分钟</span>
            </span>
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="数据库操作"><a href="#数据库操作" class="headerlink" title="数据库操作"></a>数据库操作</h3><ul>
<li>创建数据库</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">use study</span><br></pre></td></tr></table></figure>

<p>如果你想查看所有数据库，可以使用 show dbs 命令：<br>刚创建的数据库并不在数据库的列表中， 要显示它，我们需要向 数据库插入一些数据。</p>
<ul>
<li>查看当前在哪个数据库</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; db</span><br><span class="line">study</span><br></pre></td></tr></table></figure>

<a id="more"></a>
<ul>
<li>删除数据库</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.dropDatabase()</span><br></pre></td></tr></table></figure>

<!-- more -->
<h3 id="文档操作"><a href="#文档操作" class="headerlink" title="文档操作"></a>文档操作</h3><ul>
<li>向文档插入东西</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.test.insert(&#123;&quot;name&quot;:&quot;test&quot;&#125;)</span><br></pre></td></tr></table></figure>

<ul>
<li>查询文档内容</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.test.find()</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;58da1f0e767a1e8a0cedff28&quot;), &quot;name&quot; : &quot;test&quot; &#125;</span><br><span class="line"></span><br><span class="line">db.test.find().pretty() //格式化输出</span><br></pre></td></tr></table></figure>

<ul>
<li>删除文档(注意这个删掉, remove是删除数据)</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.test.drop()</span><br></pre></td></tr></table></figure>

<ul>
<li>显示文档</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; show tables;</span><br><span class="line">system.indexes</span><br><span class="line">test</span><br></pre></td></tr></table></figure>

<ul>
<li>更新文档</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">db.collection.update(</span><br><span class="line">   &lt;query&gt;,</span><br><span class="line">   &lt;update&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     upsert: &lt;boolean&gt;,</span><br><span class="line">     multi: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">参数说明：</span><br><span class="line">  ● query : update的查询条件，类似sql update查询内where后面的。</span><br><span class="line">  ● update : update的对象和一些更新的操作符（如$,$inc...）等，也可以理解为sql update查询内set后面的</span><br><span class="line">  ● upsert : 可选，这个参数的意思是，如果不存在update的记录，是否插入objNew,true为插入，默认是false，不插入。</span><br><span class="line">  ● multi : 可选，mongodb 默认是false,只更新找到的第一条记录，如果这个参数为true,就把按条件查出来多条记录全部更新。</span><br><span class="line">  ● writeConcern :可选，抛出异常的级别</span><br></pre></td></tr></table></figure>

<p>例子:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">db.col.insert(&#123;</span><br><span class="line">    title: &apos;MongoDB 教程&apos;, </span><br><span class="line">    description: &apos;MongoDB 是一个 Nosql 数据库&apos;,</span><br><span class="line">    tags: [&apos;mongodb&apos;, &apos;database&apos;, &apos;NoSQL&apos;],</span><br><span class="line">    likes: 100</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">db.col.update(&#123;&apos;title&apos;:&apos;MongoDB 教程&apos;&#125;,&#123;$set:&#123;&apos;title&apos;:&apos;MongoDB&apos;&#125;&#125;)</span><br><span class="line">db.col.update(&#123;&apos;title&apos;:&apos;MongoDB 教程&apos;&#125;,&#123;$set:&#123;&apos;title&apos;:&apos;MongoDB&apos;&#125;&#125;,&#123;multi:true&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>更多实例:</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">只更新第一条记录：</span><br><span class="line">db.col.update( &#123; &quot;count&quot; : &#123; $gt : 1 &#125; &#125; , &#123; $set : &#123; &quot;test2&quot; : &quot;OK&quot;&#125; &#125; );</span><br><span class="line">全部更新：</span><br><span class="line">db.col.update( &#123; &quot;count&quot; : &#123; $gt : 3 &#125; &#125; , &#123; $set : &#123; &quot;test2&quot; : &quot;OK&quot;&#125; &#125;,false,true );</span><br><span class="line">只添加第一条：</span><br><span class="line">db.col.update( &#123; &quot;count&quot; : &#123; $gt : 4 &#125; &#125; , &#123; $set : &#123; &quot;test5&quot; : &quot;OK&quot;&#125; &#125;,true,false );</span><br><span class="line">全部添加加进去:</span><br><span class="line">db.col.update( &#123; &quot;count&quot; : &#123; $gt : 5 &#125; &#125; , &#123; $set : &#123; &quot;test5&quot; : &quot;OK&quot;&#125; &#125;,true,true );</span><br><span class="line">全部更新：</span><br><span class="line">db.col.update( &#123; &quot;count&quot; : &#123; $gt : 15 &#125; &#125; , &#123; $inc : &#123; &quot;count&quot; : 1&#125; &#125;,false,true );</span><br><span class="line">只更新第一条记录：</span><br><span class="line">db.col.update( &#123; &quot;count&quot; : &#123; $gt : 10 &#125; &#125; , &#123; $inc : &#123; &quot;count&quot; : 1&#125; &#125;,false,false );</span><br></pre></td></tr></table></figure>

<ul>
<li>save文档</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">db.collection.save(</span><br><span class="line">   &lt;document&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br><span class="line">  ● document : 文档数据。</span><br><span class="line">  ● writeConcern :可选，抛出异常的级别。</span><br><span class="line"></span><br><span class="line">以下实例中我们替换了 _id 为 56064f89ade2f21f36b03136 的文档数据： (通过指定id替换文档)</span><br><span class="line">db.col.save(&#123;</span><br><span class="line">    &quot;_id&quot; : ObjectId(&quot;56064f89ade2f21f36b03136&quot;),</span><br><span class="line">    &quot;title&quot; : &quot;MongoDB&quot;,</span><br><span class="line">    &quot;description&quot; : &quot;MongoDB 是一个 Nosql 数据库&quot;,</span><br><span class="line">    &quot;tags&quot; : [</span><br><span class="line">            &quot;mongodb&quot;,</span><br><span class="line">            &quot;NoSQL&quot;</span><br><span class="line">    ],</span><br><span class="line">    &quot;likes&quot; : 110</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<ul>
<li>remove 文档</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">db.collection.remove(</span><br><span class="line">   &lt;query&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     justOne: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br><span class="line">  ● query :（可选）删除的文档的条件。</span><br><span class="line">  ● justOne : （可选）如果设为 true 或 1，则只删除一个文档。</span><br><span class="line">  ● writeConcern :（可选）抛出异常的级别。</span><br></pre></td></tr></table></figure>

<p>如果你想删除所有数据，可以使用以下方式（类似常规 SQL 的 truncate 命令）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.col.remove(&#123;&#125;)</span><br><span class="line">&gt;db.col.find()</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>

<h3 id="文档查询"><a href="#文档查询" class="headerlink" title="文档查询"></a>文档查询</h3><p>MongoDB 与 RDBMS Where 语句比较<br>如果你熟悉常规的 SQL 数据，通过下表可以更好的理解 MongoDB 的条件语句查询：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">操作 格式 范例 RDBMS中的类似语句</span><br><span class="line">等于 &#123;&lt;key&gt;:&lt;value&gt;&#125; db.col.find(&#123;&quot;by&quot;:&quot;菜鸟教程&quot;&#125;).pretty() where by = &apos;菜鸟教程&apos;</span><br><span class="line">小于 &#123;&lt;key&gt;:&#123;$lt:&lt;value&gt;&#125;&#125; db.col.find(&#123;&quot;likes&quot;:&#123;$lt:50&#125;&#125;).pretty() where likes &lt; 50</span><br><span class="line">小于或等于 &#123;&lt;key&gt;:&#123;$lte:&lt;value&gt;&#125;&#125; db.col.find(&#123;&quot;likes&quot;:&#123;$lte:50&#125;&#125;).pretty() where likes &lt;= 50</span><br><span class="line">大于 &#123;&lt;key&gt;:&#123;$gt:&lt;value&gt;&#125;&#125; db.col.find(&#123;&quot;likes&quot;:&#123;$gt:50&#125;&#125;).pretty() where likes &gt; 50</span><br><span class="line">大于或等于 &#123;&lt;key&gt;:&#123;$gte:&lt;value&gt;&#125;&#125; db.col.find(&#123;&quot;likes&quot;:&#123;$gte:50&#125;&#125;).pretty() where likes &gt;= 50</span><br><span class="line">不等于 &#123;&lt;key&gt;:&#123;$ne:&lt;value&gt;&#125;&#125; db.col.find(&#123;&quot;likes&quot;:&#123;$ne:50&#125;&#125;).pretty() where likes != 50</span><br></pre></td></tr></table></figure>

<ul>
<li>MongoDB AND 条件<br>MongoDB 的 find() 方法可以传入多个键(key)，每个键(key)以逗号隔开，及常规 SQL 的 AND 条件。<br>语法格式如下：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.col.find(&#123;key1:value1, key2:value2&#125;).pretty()</span><br></pre></td></tr></table></figure>

<ul>
<li>MongoDB OR 条件<br>MongoDB OR 条件语句使用了关键字 $or,语法格式如下：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.col.find(</span><br><span class="line">   &#123;</span><br><span class="line">      $or: [</span><br><span class="line">	     &#123;key1: value1&#125;, &#123;key2:value2&#125;</span><br><span class="line">      ]</span><br><span class="line">   &#125;</span><br><span class="line">).pretty()</span><br></pre></td></tr></table></figure>

<ul>
<li>AND 和 OR 联合使用<br>以下实例演示了 AND 和 OR 联合使用，类似常规 SQL 语句为： ‘where likes&gt;50 AND (by = ‘菜鸟教程’ OR title = ‘MongoDB 教程’)’</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.col.find(&#123;&quot;likes&quot;: &#123;$gt:50&#125;, $or: [&#123;&quot;by&quot;: &quot;菜鸟教程&quot;&#125;,&#123;&quot;title&quot;: &quot;MongoDB 教程&quot;&#125;]&#125;).pretty()</span><br></pre></td></tr></table></figure>

<h3 id="操作符-type-实例"><a href="#操作符-type-实例" class="headerlink" title="操作符- $type 实例"></a>操作符- $type 实例</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">类型 数字 备注</span><br><span class="line">Double 1 </span><br><span class="line">String 2 </span><br><span class="line">Object 3 </span><br><span class="line">Array 4 </span><br><span class="line">Binary data 5 </span><br><span class="line">Undefined 6 已废弃。</span><br><span class="line">Object id 7 </span><br><span class="line">Boolean 8 </span><br><span class="line">Date 9 </span><br><span class="line">Null 10 </span><br><span class="line">Regular Expression 11 </span><br><span class="line">JavaScript 13 </span><br><span class="line">Symbol 14 </span><br><span class="line">JavaScript (with scope) 15 </span><br><span class="line">32-bit integer 16 </span><br><span class="line">Timestamp 17 </span><br><span class="line">64-bit integer 18 </span><br><span class="line">Min key 255 Query with -1.</span><br><span class="line">Max key 127</span><br></pre></td></tr></table></figure>

<p>如果想获取 “col” 集合中 title 为 String 的数据，你可以使用以下命令：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.col.find(&#123;&quot;title&quot; : &#123;$type : 2&#125;&#125;)</span><br></pre></td></tr></table></figure>

<ul>
<li>Limit()方法<br>如果你需要在MongoDB中读取指定数量的数据记录，可以使用MongoDB的Limit方法，limit()方法接受一个数字参数，该参数指定从MongoDB中读取的记录条数。</li>
</ul>
<p>limit()方法基本语法如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.COLLECTION_NAME.find().limit(NUMBER)</span><br></pre></td></tr></table></figure>

<ul>
<li>Skip() 方法</li>
</ul>
<p>我们除了可以使用limit()方法来读取指定数量的数据外，还可以使用skip()方法来跳过指定数量的数据，skip方法同样接受一个数字参数作为跳过的记录条数。</p>
<p>skip() 方法脚本语法格式如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)</span><br></pre></td></tr></table></figure>

<p>看下面的这个例子, 说明find没有条件, 结果后面字段显示title, _id不显示, </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.col.find(&#123;&#125;,&#123;&quot;title&quot;:1,_id:0&#125;).limit(1).skip(1)</span><br><span class="line">&#123; &quot;title&quot; : &quot;Java 教程&quot; &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>Sort()方法<br>在MongoDB中使用使用sort()方法对数据进行排序，sort()方法可以通过参数指定排序的字段，并使用 1 和 -1 来指定排序的方式，其中 1 为升序排列，而-1是用于降序排列。</li>
</ul>
<p>sort()方法基本语法如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.COLLECTION_NAME.find().sort(&#123;KEY:1&#125;)</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.col.find(&#123;&#125;,&#123;&quot;title&quot;:1,_id:0&#125;).sort(&#123;&quot;likes&quot;:-1&#125;)</span><br><span class="line">&#123; &quot;title&quot; : &quot;PHP 教程&quot; &#125;</span><br><span class="line">&#123; &quot;title&quot; : &quot;Java 教程&quot; &#125;</span><br><span class="line">&#123; &quot;title&quot; : &quot;MongoDB 教程&quot; &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>

<h3 id="索引"><a href="#索引" class="headerlink" title="索引:"></a>索引:</h3><p>ensureIndex() 方法<br>ensureIndex()方法基本语法格式如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.COLLECTION_NAME.ensureIndex(&#123;KEY:1&#125;)</span><br></pre></td></tr></table></figure>

<p>语法中 Key 值为你要创建的索引字段，1为指定按升序创建索引，如果你想按降序来创建索引指定为-1即可。</p>
<p>ensureIndex() 方法中你也可以设置使用多个字段创建索引（关系型数据库中称作复合索引）。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.col.ensureIndex(&#123;&quot;title&quot;:1,&quot;description&quot;:-1&#125;)</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>

<p>ensureIndex() 接收可选参数，可选参数列表如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Parameter Type Description</span><br><span class="line">background Boolean 建索引过程会阻塞其它数据库操作，background可指定以后台方式创建索引，即增加 &quot;background&quot; 可选参数。 &quot;background&quot; 默认值为false。</span><br><span class="line">unique Boolean 建立的索引是否唯一。指定为true创建唯一索引。默认值为false.</span><br><span class="line">name string 索引的名称。如果未指定，MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。</span><br><span class="line">dropDups Boolean 在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false.</span><br><span class="line">sparse Boolean 对文档中不存在的字段数据不启用索引；这个参数需要特别注意，如果设置为true的话，在索引字段中不会查询出不包含对应字段的文档.。默认值为 false.</span><br><span class="line">expireAfterSeconds integer 指定一个以秒为单位的数值，完成 TTL设定，设定集合的生存时间。</span><br><span class="line">v index version 索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。</span><br><span class="line">weights document 索引权重值，数值在 1 到 99,999 之间，表示该索引相对于其他索引字段的得分权重。</span><br><span class="line">default_language string 对于文本索引，该参数决定了停用词及词干和词器的规则的列表。 默认为英语</span><br><span class="line">language_override string 对于文本索引，该参数指定了包含在文档中的字段名，语言覆盖默认的language，默认值为 language.</span><br></pre></td></tr></table></figure>

<p>在后台创建索引：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.values.ensureIndex(&#123;open: 1, close: 1&#125;, &#123;background: true&#125;)</span><br></pre></td></tr></table></figure>

<p>通过在创建索引时加background:true 的选项，让创建工作在后台执行</p>
<h3 id="聚合"><a href="#聚合" class="headerlink" title="聚合:"></a>聚合:</h3><p>MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等)，并返回计算后的数据结果。有点类似sql语句中的 count(*)。</p>
<p>aggregate() 方法的基本语法格式如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.col.find().pretty()</span><br><span class="line">&#123;</span><br><span class="line">	&quot;_id&quot; : ObjectId(&quot;58dc7efc70d2b5b8821b6184&quot;),</span><br><span class="line">	&quot;title&quot; : &quot;MongoDB Overview&quot;,</span><br><span class="line">	&quot;description&quot; : &quot;MongoDB is no sql database&quot;,</span><br><span class="line">	&quot;by_user&quot; : &quot;w3cschool.cc&quot;,</span><br><span class="line">	&quot;url&quot; : &quot;http://www.w3cschool.cc&quot;,</span><br><span class="line">	&quot;tags&quot; : [</span><br><span class="line">		&quot;mongodb&quot;,</span><br><span class="line">		&quot;database&quot;,</span><br><span class="line">		&quot;NoSQL&quot;</span><br><span class="line">	],</span><br><span class="line">	&quot;likes&quot; : 100</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">	&quot;_id&quot; : ObjectId(&quot;58dc7fcb70d2b5b8821b6185&quot;),</span><br><span class="line">	&quot;title&quot; : &quot;NoSQL Overview&quot;,</span><br><span class="line">	&quot;description&quot; : &quot;No sql database is very fast&quot;,</span><br><span class="line">	&quot;by_user&quot; : &quot;w3cschool.cc&quot;,</span><br><span class="line">	&quot;url&quot; : &quot;http://www.w3cschool.cc&quot;,</span><br><span class="line">	&quot;tags&quot; : [</span><br><span class="line">		&quot;mongodb&quot;,</span><br><span class="line">		&quot;database&quot;,</span><br><span class="line">		&quot;NoSQL&quot;</span><br><span class="line">	],</span><br><span class="line">	&quot;likes&quot; : 10</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">	&quot;_id&quot; : ObjectId(&quot;58dc7fe370d2b5b8821b6186&quot;),</span><br><span class="line">	&quot;title&quot; : &quot;Neo4j Overview&quot;,</span><br><span class="line">	&quot;description&quot; : &quot;Neo4j is no sql database&quot;,</span><br><span class="line">	&quot;by_user&quot; : &quot;Neo4j&quot;,</span><br><span class="line">	&quot;url&quot; : &quot;http://www.neo4j.com&quot;,</span><br><span class="line">	&quot;tags&quot; : [</span><br><span class="line">		&quot;neo4j&quot;,</span><br><span class="line">		&quot;database&quot;,</span><br><span class="line">		&quot;NoSQL&quot;</span><br><span class="line">	],</span><br><span class="line">	&quot;likes&quot; : 750</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.col.aggregate([&#123;$group:&#123;_id:&quot;$by_user&quot;, num_tutorial:&#123;$sum:1&#125;&#125;&#125;])</span><br><span class="line">&#123; &quot;_id&quot; : &quot;Neo4j&quot;, &quot;num_tutorial&quot; : 1 &#125;</span><br><span class="line">&#123; &quot;_id&quot; : &quot;w3cschool.cc&quot;, &quot;num_tutorial&quot; : 2 &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>

<p>以上实例类似sql语句： select by_user, count(*) from mycol group by by_user</p>
<p>//上面的_id不能变, 后面的字段可以自己指定</p>
<p>下表展示了一些聚合的表达式:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">表达式 描述 实例</span><br><span class="line">$sum 计算总和。 db.mycol.aggregate([&#123;$group : &#123;_id : &quot;$by_user&quot;, num_tutorial : &#123;$sum : &quot;$likes&quot;&#125;&#125;&#125;])</span><br><span class="line">$avg 计算平均值 db.mycol.aggregate([&#123;$group : &#123;_id : &quot;$by_user&quot;, num_tutorial : &#123;$avg : &quot;$likes&quot;&#125;&#125;&#125;])</span><br><span class="line">$min 获取集合中所有文档对应值得最小值。 db.mycol.aggregate([&#123;$group : &#123;_id : &quot;$by_user&quot;, num_tutorial : &#123;$min : &quot;$likes&quot;&#125;&#125;&#125;])</span><br><span class="line">$max 获取集合中所有文档对应值得最大值。 db.mycol.aggregate([&#123;$group : &#123;_id : &quot;$by_user&quot;, num_tutorial : &#123;$max : &quot;$likes&quot;&#125;&#125;&#125;])</span><br><span class="line">$push 在结果文档中插入值到一个数组中。 db.mycol.aggregate([&#123;$group : &#123;_id : &quot;$by_user&quot;, url : &#123;$push: &quot;$url&quot;&#125;&#125;&#125;])</span><br><span class="line">$addToSet 在结果文档中插入值到一个数组中，但不创建副本。 db.mycol.aggregate([&#123;$group : &#123;_id : &quot;$by_user&quot;, url : &#123;$addToSet : &quot;$url&quot;&#125;&#125;&#125;])</span><br><span class="line">$first 根据资源文档的排序获取第一个文档数据。 db.mycol.aggregate([&#123;$group : &#123;_id : &quot;$by_user&quot;, first_url : &#123;$first : &quot;$url&quot;&#125;&#125;&#125;])</span><br><span class="line">$last 根据资源文档的排序获取最后一个文档数据 db.mycol.aggregate([&#123;$group : &#123;_id : &quot;$by_user&quot;, last_url : &#123;$last : &quot;$url&quot;&#125;&#125;&#125;])</span><br></pre></td></tr></table></figure>

<h3 id="管道"><a href="#管道" class="headerlink" title="管道"></a>管道</h3><p>  ● $project：修改输入文档的结构。可以用来重命名、增加或删除域，也可以用于创建计算结果以及嵌套文档。</p>
<p>  ● $match：用于过滤数据，只输出符合条件的文档。$match使用MongoDB的标准查询操作。</p>
<p>  ● $limit：用来限制MongoDB聚合管道返回的文档数。</p>
<p>  ● $skip：在聚合管道中跳过指定数量的文档，并返回余下的文档。</p>
<p>  ● $unwind：将文档中的某一个数组类型字段拆分成多条，每条包含数组中的一个值。</p>
<p>  ● $group：将集合中的文档分组，可用于统计结果。</p>
<p>  ● $sort：将输入文档排序后输出。</p>
<p>  ● $geoNear：输出接近某一地理位置的有序文档。</p>
<p>1、$project实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">db.article.aggregate(</span><br><span class="line">    &#123; $project : &#123;</span><br><span class="line">        title : 1 ,</span><br><span class="line">        author : 1 ,</span><br><span class="line">    &#125;&#125;</span><br><span class="line"> );</span><br></pre></td></tr></table></figure>

<p>这样的话结果中就只还有_id,tilte和author三个字段了，默认情况下_id字段是被包含的，如果要想不包含_id话可以这样:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">db.article.aggregate(</span><br><span class="line">    &#123; $project : &#123;</span><br><span class="line">        _id : 0 ,</span><br><span class="line">        title : 1 ,</span><br><span class="line">        author : 1</span><br><span class="line">    &#125;&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.find()</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;58dca39270d2b5b8821b6187&quot;), &quot;name&quot; : &quot;liuwei&quot;, &quot;age&quot; : 123 &#125;</span><br><span class="line">&gt; db.article.aggregate(     &#123; $project : &#123;      name:1    &#125;&#125;  );</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;58dca39270d2b5b8821b6187&quot;), &quot;name&quot; : &quot;liuwei&quot; &#125;</span><br><span class="line">&gt; db.article.find(&#123;&#125;, &#123;name:1&#125;)</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;58dca39270d2b5b8821b6187&quot;), &quot;name&quot; : &quot;liuwei&quot; &#125;</span><br></pre></td></tr></table></figure>

<p>2.$match实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.articles.aggregate( [</span><br><span class="line">                        &#123; $match : &#123; score : &#123; $gt : 70, $lte : 90 &#125; &#125; &#125;,</span><br><span class="line">                        &#123; $group: &#123; _id: null, count: &#123; $sum: 1 &#125; &#125; &#125;</span><br><span class="line">                       ] );</span><br></pre></td></tr></table></figure>

<p>$match用于获取分数大于70小于或等于90记录，然后将符合条件的记录送到下一阶段$group管道操作符进行处理。</p>
<p>3.$skip实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.article.aggregate(</span><br><span class="line">    &#123; $skip : 5 &#125;);</span><br></pre></td></tr></table></figure>

<p>经过$skip管道操作符处理后，前五个文档被”过滤”掉。</p>
<h3 id="数据库引用"><a href="#数据库引用" class="headerlink" title="数据库引用:"></a>数据库引用:</h3><p>DBRef的形式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123; $ref : , $id : , $db :  &#125;</span><br><span class="line">三个字段表示的意义为：</span><br><span class="line">  ● $ref：集合名称</span><br><span class="line">  ● $id：引用的id</span><br><span class="line">  ● $db:数据库名称，可选参数</span><br></pre></td></tr></table></figure>

<p>address DBRef 字段指定了引用的地址文档是在 address_home 集合下的 w3cschoolcc 数据库，id 为 534009e4d852427820000002。<br>以下代码中，我们通过指定 $ref 参数（address_home 集合）来查找集合中指定id的用户地址信息：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt;var user = db.users.findOne(&#123;&quot;name&quot;:&quot;Tom Benzamin&quot;&#125;)</span><br><span class="line">&gt;var dbRef = user.address</span><br><span class="line">&gt;db[dbRef.$ref].findOne(&#123;&quot;_id&quot;:(dbRef.$id)&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="使用-explain"><a href="#使用-explain" class="headerlink" title="使用 explain()"></a>使用 explain()</h3><p>explain 操作提供了查询信息，使用索引及查询统计等。有利于我们对索引的优化。<br>接下来我们在 users 集合中创建 gender 和 user_name 的索引：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.users.find(&#123;gender:&quot;M&quot;&#125;,&#123;user_name:1,_id:0&#125;).explain()</span><br></pre></td></tr></table></figure>

<h3 id="使用-hint"><a href="#使用-hint" class="headerlink" title="使用 hint()"></a>使用 hint()</h3><p>虽然MongoDB查询优化器一般工作的很不错，但是也可以使用 hint 来强制 MongoDB 使用一个指定的索引。<br>这种方法某些情形下会提升性能。 一个有索引的 collection 并且执行一个多字段的查询(一些字段已经索引了)。<br>如下查询实例指定了使用 gender 和 user_name 索引字段来查询：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;db.users.find(&#123;gender:&quot;M&quot;&#125;,&#123;user_name:1,_id:0&#125;).hint(&#123;gender:1,user_name:1&#125;)</span><br></pre></td></tr></table></figure>


    </div>

    
    
    
        
      
        <div id="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作, 一个耿直的笑脸~</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Levon 微信支付">
        <p>微信支付</p>
      </div>
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="Levon 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/sql/" rel="tag"># sql</a>
            
              <a href="/tags/mongodb/" rel="tag"># mongodb</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/p/6556ac6a.html" rel="next" title="c++stl容器循环earse用法">
                  <i class="fa fa-chevron-left"></i> c++stl容器循环earse用法
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/p/9ecea432.html" rel="prev" title="iOS录音遇到的问题">
                  iOS录音遇到的问题 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    
  <div class="comments" id="comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
    </div>
  </div>
  
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#数据库操作"><span class="nav-number">1.</span> <span class="nav-text">数据库操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文档操作"><span class="nav-number">2.</span> <span class="nav-text">文档操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文档查询"><span class="nav-number">3.</span> <span class="nav-text">文档查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#操作符-type-实例"><span class="nav-number">4.</span> <span class="nav-text">操作符- $type 实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#索引"><span class="nav-number">5.</span> <span class="nav-text">索引:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#聚合"><span class="nav-number">6.</span> <span class="nav-text">聚合:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#管道"><span class="nav-number">7.</span> <span class="nav-text">管道</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据库引用"><span class="nav-number">8.</span> <span class="nav-text">数据库引用:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用-explain"><span class="nav-number">9.</span> <span class="nav-text">使用 explain()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用-hint"><span class="nav-number">10.</span> <span class="nav-text">使用 hint()</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/avatar.jpg"
      alt="Levon">
  <p class="site-author-name" itemprop="name">Levon</p>
  <div class="site-description" itemprop="description">Never Give Up</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">127</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">76</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/unix2dos" title="GitHub &rarr; https://github.com/unix2dos" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:levonfly@gmail.com" title="E-Mail &rarr; mailto:levonfly@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://twitter.com/levonfly" title="Twitter &rarr; https://twitter.com/levonfly" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://weibo.com/l6241425" title="Weibo &rarr; https://weibo.com/l6241425" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Levon</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">507k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:41</span>
</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>








  <script src="/js/local-search.js?v=7.4.0"></script>














  

  

  

<script>
  function loadCount() {
    var d = document, s = d.createElement('script');
    s.src = 'https://levonfly.disqus.com/count.js';
    s.id = 'dsq-count-scr';
    (d.head || d.body).appendChild(s);
  }
  // defer loading until the whole page loading is completed
  window.addEventListener('load', loadCount, false);
</script>
<script>
  function disqus_config() {
    this.page.url = "https://unix2dos.github.io/p/d34774ef.html";
    this.page.identifier = "p/d34774ef.html";
    this.page.title = 'mongodb操作教程';};
  function loadComments() {
    if (window.DISQUS) {
      DISQUS.reset({
        reload: true,
        config: disqus_config
      });
    } else {
      var d = document, s = d.createElement('script');
      s.src = 'https://levonfly.disqus.com/embed.js';
      s.setAttribute('data-timestamp', '' + +new Date());
      (d.head || d.body).appendChild(s);
    }
  }
    window.addEventListener('load', loadComments, false);
  
</script>

</body>
</html>
